package com.kancy.jemeter.functions;

import com.kancy.jemeter.util.MessageUtil;
import com.kancy.jemeter.util.RandomUtil;
import com.kancy.jemeter.util.StringUtil;
import org.apache.jmeter.functions.InvalidVariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;

import java.util.LinkedList;
import java.util.List;

/**
 * @author kancy
 * @date 2019/6/29 20:15
 */
public class RandomCharFunction extends JemeterAbstractFunction {

	public RandomCharFunction() {
		super(0,3);
	}

	@Override
	public String execute(SampleResult sampleResult, Sampler sampler) throws InvalidVariableException {
		String src = getParameter(0, "");
		if(StringUtil.isEmpty(src)){
			return setJMeterVariable(2, "");
		}

		String splitChar = getParameter(1, "");
		if (StringUtil.isEmpty(splitChar)){
			char[] chars = src.toCharArray();
			return setJMeterVariable(2,
					String.valueOf(chars[RandomUtil.nextInt(0, chars.length)]));
		}

		String[] split = StringUtil.split(src, splitChar);
		return setJMeterVariable(2,
				String.valueOf(split[RandomUtil.nextInt(0, split.length)]));

	}
	private static final List<String> argumentDesclist = new LinkedList();

	static {
		argumentDesclist.add(MessageUtil.getResString("__randomchar.src.message"));
		argumentDesclist.add(MessageUtil.getResString("__randomchar.split.message"));
		argumentDesclist.add(MessageUtil.getResString("varname.message"));
	}
	@Override
	public List<String> getArgumentDesc() {
		return argumentDesclist;
	}
}
